package com.irdstudio.apicenter.gateway.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.MaccsPacketUtil;
import com.irdstudio.apicenter.gateway.core.jdbc.MaccsBaseDAO;
import com.irdstudio.apicenter.gateway.util.spring.BeanUtils;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;
/**
 * 应用权限菜单数据交易
 * @author zs.ligm
 * @version 1.0
 * @date 2015-07-31
 */
@Controller
public class AppMenuRights implements IController{
	
	/* 文本日志输出 */
	private static final Logger logger = LoggerFactory
			.getLogger(AppMenuRights.class);
	
	/* 用户有权限访问菜单查询语句*/
	private static final String queryMenuSql = "SELECT t2. * "
			+ " FROM (SELECT DISTINCT (menu_id) menu_id "
			+ "      FROM (SELECT app_id, "
			+ "                   app_role_id "
			+ "            FROM app_user_role "
			+ "            WHERE app_id = ? "
			+ "            AND   app_userid = ?) a "
			+ "           INNER JOIN app_role_right b ON a.app_id = b.app_id AND a.app_role_id = b.app_role_id) t1"
			+ "     INNER JOIN app_menu_resource t2 ON t1.menu_id = t2.menu_id  and  t2.app_id = ? "
			+ " ORDER BY menu_sort_no";

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket,
			HttpServletRequest request, HttpServletResponse response)
			throws MaccsException {
		
		// 接收移动客户端传过来的参数
		String appId = inPacket.getValue("appId");
		
		// 资源权限共享应用ID
		String shareAppId = inPacket.getValue("shareAppId");
		
		// 请求权限数据的APP用户ID
		String appUserId = inPacket.getValue("appUserId");
		
		// 请求权限数据的APP用户ID必须传入
		if(StringUtils.isEmpty(appUserId)){
			return new JsonView(request, response, MaccsPacketUtil
					.makeFailurePacket("未接收到应用用户ID参数!"));
		}
		
		logger.debug("appId:" + appId + ",shareAppId:" + shareAppId
				+ ",appUserId=" + appUserId);
		
		//如果的指定的资源共享的应用ID的话，以此appId去请求权限
		if (!StringUtils.isEmpty(shareAppId)) {
			appId = shareAppId;
		}
		
		// 获取APP用户数据权限 
		MaccsBaseDAO jdbcDao = BeanUtils.getBean(MaccsBaseDAO.class);
		List<Map<String, Object>> menus = jdbcDao.findMapList(queryMenuSql,
				new Object[] { appId, appUserId,appId });
		
		if (menus.size() < 1) {
			return new JsonView(request, response, MaccsPacketUtil
					.makeFailurePacket("无可访问菜单!"));
		} else {
			MaccsPacket outPacket = MaccsPacketUtil
					.makeSimpleSuccessPacket("OK!");
			outPacket.addVariable("menus", menus);
			return new JsonView(request, response, outPacket);
		}
	}

}
